﻿using System.Windows;

namespace Chenglin.WPJigsawPuzzle
{
    public class MarginAnimationWrapper : FrameworkElement
    {
        /*
         * Using DependencyProperty as the backing store. This enables animation, styling, binding, etc...
         */
        public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(MarginAnimationWrapper), new PropertyMetadata(0.0, OnValueChanged));
        public static readonly DependencyProperty TargetProperty = DependencyProperty.Register("Target", typeof(FrameworkElement), typeof(MarginAnimationWrapper), new PropertyMetadata(null, OnTargetChanged));

        public FrameworkElement Target
        {
            get { return (FrameworkElement)GetValue(TargetProperty); }
            set { SetValue(TargetProperty, value); }
        }

        public double Value
        {
            get { return (double)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

        private static void OnTargetChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
        {
            MarginAnimationWrapper sender = (MarginAnimationWrapper)source;
            sender.UpdateMargin();
        }

        private static void OnValueChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
        {
            MarginAnimationWrapper sender = (MarginAnimationWrapper)source;
            sender.UpdateMargin();
        }

        private void UpdateMargin()
        {
            var targetElement = Target;
            if (targetElement != null)
            {
                double val = Value;
                targetElement.Margin = new Thickness(-val / 2, val, val / 2, -val);
            }
        }
    }
}
